package dao

import (
	"context"
	"fileNest/global"
	"fmt"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 单个查询
func DBFindOne(collectionName string, filter bson.M, result interface{}) (err error) {
	err = global.DB.Collection(collectionName).FindOne(context.Background(), filter).Decode(result)
	return
}

// 分页查询
func DBFindMoreWithPage(collectionName string, filter bson.M, findOptions *options.FindOptions, result interface{}) (err error) {
	cursor, err := global.DB.Collection(collectionName).Find(context.Background(), filter, findOptions)
	if err != nil {
		return
	}
	defer cursor.Close(context.Background())
	if err = cursor.All(context.Background(), result); err != nil {
		return
	}
	return
}

// 不分页查询
func DBFindMoreWithOutPage(collectionName string, filter bson.M, result interface{}) (err error) {
	// findOptions := options.Find().SetSort(bson.D{{Key: "parent_id", Value: -1}})
	cursor, err := global.DB.Collection(collectionName).Find(context.Background(), filter)
	if err != nil {
		return
	}
	defer cursor.Close(context.Background())
	if err = cursor.All(context.Background(), result); err != nil {
		return
	}
	return
}

// 单个新增
func DBAdd(collectionName string, value interface{}) (insertedID primitive.ObjectID, err error) {
	result, err := global.DB.Collection(collectionName).InsertOne(context.Background(), value)
	if err != nil {
		return
	}
	insertedID, ok := result.InsertedID.(primitive.ObjectID)
	if !ok {
		err = fmt.Errorf("ObjectID断言失败")
	}
	return
}

// 批量新增
func DBAddMany(collectionName string, value interface{}) (err error) {
	return
}

// 单个删除
func DeleteOne(collectionName, id string) (err error) {
	objectID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return fmt.Errorf("invalid ObjectID: %v", err)
	}
	var filter = bson.M{
		"_id": objectID,
	}
	_, err = global.DB.Collection(collectionName).DeleteOne(context.Background(), filter)
	return
}

// 批量删除
func DeleteMany(collectionName string, filter bson.M) (err error) {
	_, err = global.DB.Collection(collectionName).DeleteMany(context.Background(), filter)
	return
}

// 单个更新
func UpdateOne(collectionName string, filter, update bson.M) (result interface{}, err error) {
	result, err = global.DB.Collection(collectionName).UpdateOne(context.Background(), filter, update)
	return
}

// 批量更新
func UpdateMany(collectionName string, filter, update bson.M) (result interface{}, err error) {
	result, err = global.DB.Collection(collectionName).UpdateMany(context.Background(), filter, update)
	return
}
